package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chagee.base.exception.SoaException;
import com.chagee.base.utils.SoaResponse;
import com.chagee.base.utils.SoaUtil;
import com.chagee.scm.api.supplier.request.QuerySupplierRequestBo;
import com.chagee.scm.api.supplier.response.SupplierSimpleInfoBO;
import com.chagee.scm.api.supplier.service.SupplierServiceApi;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 刷新工单评分数据
 * @Author : hk
 * @Date : 2025/2/06
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class RefreshOrderScoreHandler {

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private WorkOrderReceiverMapper workOrderReceiverMapper;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	/**
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("refreshOrderScoreHandler")
	public ReturnT<String> refreshOrderScoreHandler(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("刷新工单评分定时任务开始,traceId :{}", span.getTraceId());
		try {

			int startIndex = 0;
			while (true) {
				log.info("start_index " + startIndex);
				LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.isNotNull(WorkOrderDO::getDocumentScore);
				queryWrapper.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
				queryWrapper.gt(WorkOrderDO::getId, startIndex);
				queryWrapper.orderByAsc(WorkOrderDO::getId);
				queryWrapper.last(CommonConstant.LIMIT_SIZE_SQL);
				List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(queryWrapper);

				if (CollectionUtils.isEmpty(workOrderDOList)) {
					break;
				}

				for (WorkOrderDO workOrderDO : workOrderDOList) {
					try {
						LambdaQueryWrapper<WorkOrderReceiverDO> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
						wrapper.eq(WorkOrderReceiverDO::getWorkOrderNumber, workOrderDO.getWorkOrderNumber());
						List<WorkOrderReceiverDO> workOrderReceiverDOS = workOrderReceiverMapper.selectList(wrapper);
						if (CollectionUtils.isEmpty(workOrderReceiverDOS)) {
							continue;
						}
						updateScore(workOrderReceiverDOS, workOrderDO.getDocumentScore());

					} catch (Exception e) {
						log.error("刷新工单评分定时任务异常:工单号 : {}, storeId:{}, startIndex:{} 异常信息 : ", workOrderDO.getWorkOrderNumber(), workOrderDO.getStoreCode(), startIndex, e);
					}
				}
				startIndex = Math.toIntExact(workOrderDOList.stream().map(WorkOrderDO::getId).max(Comparator.naturalOrder()).orElse(0L));

			}
		} catch (Exception e) {
			XxlJobLogger.log("刷新工单评分定时任务异常，异常信息:", e);
			log.error("刷新工单评分定时任务异常 => param : {} => 异常信息: ", param, e);
		}
		XxlJobLogger.log("刷新工单评分定时任务结束，traceId :{},共耗时:{}", span.getTraceId(), timer.intervalRestart());
		return ReturnT.SUCCESS;
	}

	public void updateScore(List<WorkOrderReceiverDO> workOrderReceiverDOS, String score) {
		workOrderReceiverDOS.forEach(s -> {
			LambdaUpdateWrapper<WorkOrderReceiverDO> wrapper = new LambdaUpdateWrapper<>();
			wrapper.eq(WorkOrderReceiverDO::getId, s.getId());
			wrapper.set(WorkOrderReceiverDO::getDocumentScore, score);
			workOrderReceiverMapper.update(wrapper);
		});
	}


}
